// https://www.lintcode.com/problem/word-break/my-submissions

class Solution {
public:
    /*
     * @param s: A string
     * @param dict: A dictionary of words dict
     * @return: A boolean
     */
    bool wordBreak(string s, unordered_set<string> dict) {
        // 95%, MLE
        // if ((dict.empty() && s == "")|| dict.find(s) != dict.end()) return true;
        // for (int i = 1; i < s.size(); ++i)
        // {
        //     if (dict.find(s.substr(0, i)) != dict.end())
        //     {
        //         if (wordBreak(s.substr(i, s.size() - i), dict)) return true;
        //     }
        // }
        // return false;
        
        // 91%, 如果不记录maxlen的话TLE
        int len = s.length();
        vector<bool> canSeg(len + 1, false);
        int maxLen = 0;
        for (auto i: dict)
        {
            if (i.length() > maxLen) maxLen = i.length();
        }
        canSeg[0] = true;
        for (int i = 1; i <= len; ++i)
        {
            int j = i - 1;
            for (; j >= i - maxLen && j >= 0; --j) //注意判断>=i-maxLen,还要判断>=0
            {
                if (canSeg[j] && dict.find(s.substr(j, i - j)) != dict.end())
                {
                    canSeg[i] = true;
                    break;
                }
            }
        }
        return canSeg[len];
    }
};